<template>
  <div class="workorder-list-container">
    <el-card>
      <!-- 筛选栏 -->
      <div class="filter-container">
        <el-select v-model="filter.status" placeholder="按状态筛选" @change="loadWorkOrders">
          <el-option label="全部" value="" />
          <el-option label="待处理" value="待处理" />
          <el-option label="待分配站点" value="待分配站点" />
          <el-option label="待分派维修员" value="待分派维修员" />
          <el-option label="待预约" value="待预约" />
          <el-option label="待上门服务" value="待上门服务" />
          <el-option label="待客服回访" value="待客服回访" />
          <el-option label="已完成" value="已完成" />
        </el-select>

        <el-select v-model="filter.sort" placeholder="排序方式" @change="loadWorkOrders">
          <el-option label="最新创建" value="-createdAt" />
          <el-option label="最早创建" value="createdAt" />
          <el-option label="最新更新" value="-updatedAt" />
          <el-option label="最早更新" value="updatedAt" />
        </el-select>
      </div>

      <!-- 工单表格 -->

      <!-- 使用通用表格组件 -->
      <CommonTable
        :columns="tableColumns"
        :table-data="workOrderList"
        :is-loading="isLoading"
        :action-config="actionTableConfig"
        :pagination="paginationConfig"
        @page-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
      <!-- 分配站点模态框 -->
      <el-dialog
        v-model="showAssignDialog"
        title="分配维修站点"
        width="30%"
        :before-close="handleDialogClose"
      >
        <el-form :model="assignForm" label-width="80px">
          <el-form-item label="选择站点">
            <el-select
              v-model="assignForm.station_id"
              placeholder="请选择维修站点"
              :disabled="isAssignLoading"
            >
              <el-option
                v-for="station in stationList"
                :key="station.id"
                :label="station.name"
                :value="station.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showAssignDialog = false" :disabled="isAssignLoading"
              >取消</el-button
            >
            <el-button
              type="primary"
              @click="confirmAssign"
              :loading="isAssignLoading"
              :disabled="!assignForm.station_id || isAssignLoading"
            >
              确认分配
            </el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { getAllWorkOrders, getWorkOrdersByStatus, assignStationByAdmin } from '@/api/workOrder' // 假设接口路径正确
import { ElMessage } from 'element-plus'
import { getStations } from '@/api/user' // 从user.js获取站点列表接口

import CommonTable from '@/components/CommonTable.vue'

// 表格列配置
const tableColumns = [
  { prop: '_id', label: '工单编号', width: '180' },
  { prop: 'customer_name', label: '客户姓名', width: '120' },
  { prop: 'customer_phone', label: '联系电话', width: '150' },
  { prop: 'user_claim', label: '问题描述', minWidth: '200' },
  { prop: 'status', label: '状态', width: '100' },
  { prop: 'updatedAt', label: '创建时间', width: '180' },
]
// 状态管理
const workOrderList = ref([])
const isLoading = ref(false)
const total = ref(0) // 总记录数

const showAssignDialog = ref(false) //分配模态框显示状态
const assignForm = ref({ station_id: '' }) // 分配表单数据
const currentOrderId = ref('') // 当前操作的工单ID
const isAssignLoading = ref(false) // 分配操作加载状态
const stationList = ref([]) // 维修站点列表

// 操作列配置
const actionTableConfig = {
  label: '操作',
  width: '120',
  text: '分配站点',
  condition: (row) => row.status === '待分配站点',
  handler: (row) => handleAssignStation(row),
}

const paginationConfig = computed(() => ({
  total: total.value,
  currentPage: filter.value.page,
  pageSize: filter.value.limit,
}))
const loadStations = async () => {
  try {
    const res = await getStations() // 调用user.js中的getStations接口获取站点列表
    if (res.code === 200) {
      stationList.value = res.data.map((item) => ({
        id: item._id,
        name: item.name, // 假设站点数据包含name字段，根据实际接口调整
      }))
      console.log(stationList)
    }
  } catch (err) {
    ElMessage.error('获取站点列表失败', err)
  }
}
// 点击分配站点按钮
const handleAssignStation = (row) => {
  currentOrderId.value = row._id // 假设工单数据包含id字段
  assignForm.value.station_id = '' // 重置选择
  showAssignDialog.value = true
  loadStations() // 打开模态框时刷新站点列表
}

// 确认分配
const confirmAssign = async () => {
  console.log('currentOrderId', currentOrderId.value, 'assignForm', assignForm.value)

  if (!currentOrderId.value || !assignForm.value.station_id) return

  isAssignLoading.value = true
  try {
    const res = await assignStationByAdmin(currentOrderId.value, {
      station_id: assignForm.value.station_id,
    })
    if (res.code === 200) {
      ElMessage.success('站点分配成功')
      showAssignDialog.value = false
      loadWorkOrders() // 刷新工单列表
    } else {
      ElMessage.error(res.message || '分配失败')
    }
  } catch (err) {
    ElMessage.error('网络请求失败', err)
  } finally {
    isAssignLoading.value = false
  }
}

// 关闭模态框
const handleDialogClose = () => {
  showAssignDialog.value = false
  currentOrderId.value = ''
}
// 筛选参数（与接口参数匹配）
const filter = ref({
  page: 1, // 当前页
  limit: 10, // 每页数量
  sort: '-createdAt', // 默认排序（最新创建）
  status: '', // 状态筛选（空为全部）
})

// 状态文本映射

// 加载工单数据
const loadWorkOrders = async () => {
  isLoading.value = true
  try {
    let res
    // 根据是否有状态筛选选择接口
    if (filter.value.status) {
      res = await getWorkOrdersByStatus({
        ...filter.value,
        status: filter.value.status,
      })
    } else {
      res = await getAllWorkOrders(filter.value)
    }

    if (res.code === 200 && res.data.orders) {
      workOrderList.value = res.data.orders
      console.log(workOrderList.value)

      total.value = res.data.total // 假设接口返回total字段
    } else if (res.code === 200 && res.data) {
      workOrderList.value = res.data
    } else {
      ElMessage.error(res.message || '获取工单失败')
    }
  } catch (err) {
    ElMessage.error('网络请求失败', err)
  } finally {
    isLoading.value = false
  }
}

// 分页-页码变化
const handleCurrentChange = (page) => {
  filter.value.page = page
  loadWorkOrders()
}

// 分页-每页数量变化
const handleSizeChange = (limit) => {
  filter.value.limit = limit
  filter.value.page = 1 // 重置为第一页
  loadWorkOrders()
}

// 辅助函数：状态转文本

// 初始化加载数据
loadWorkOrders()
</script>

<style scoped>
.workorder-list-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.filter-container {
  margin-bottom: 20px;
  display: flex;
  gap: 20px;
}
</style>
